// 统一的性能监控工具
import { log, LogCategory } from '../utils/logger';

interface RenderMetrics {
  renderCount: number;
  renderTime: number;
  skippedRenders: number;
  totalFields: number;
  timestamp: number;
}

interface FieldRenderMetrics {
  [fieldId: string]: {
    renderCount: number;
    lastRenderTime: number;
    skippedCount: number;
  };
}

interface TimerMetrics {
  count: number;
  average: number;
  total: number;
}

export class UnifiedPerformanceMonitor {
  private static instance: UnifiedPerformanceMonitor;

  // 渲染监控相关
  private renderMetrics: RenderMetrics = {
    renderCount: 0,
    renderTime: 0,
    skippedRenders: 0,
    totalFields: 0,
    timestamp: Date.now()
  };
  private fieldMetrics: FieldRenderMetrics = {};
  private isRenderMonitoringEnabled = false;

  // 通用计时相关
  private timers: Map<string, number> = new Map();
  private timerMetrics: Map<string, number[]> = new Map();

  constructor() {
    this.reset();
  }

  static getInstance(): UnifiedPerformanceMonitor {
    if (!UnifiedPerformanceMonitor.instance) {
      UnifiedPerformanceMonitor.instance = new UnifiedPerformanceMonitor();
    }
    return UnifiedPerformanceMonitor.instance;
  }

  // ==================== 渲染性能监控 ====================

  enableRenderMonitoring() {
    this.isRenderMonitoringEnabled = true;
    log.performanceMonitor(LogCategory.PERFORMANCE_MONITOR, 'enable');
  }

  disableRenderMonitoring() {
    this.isRenderMonitoringEnabled = false;
    log.performanceMonitor(LogCategory.PERFORMANCE_MONITOR, 'disable');
  }

  startRender(fieldId: string) {
    if (!this.isRenderMonitoringEnabled) return;

    if (!this.fieldMetrics[fieldId]) {
      this.fieldMetrics[fieldId] = {
        renderCount: 0,
        lastRenderTime: 0,
        skippedCount: 0
      };
    }

    this.fieldMetrics[fieldId].lastRenderTime = performance.now();
    // 移除这里的 renderCount++，只在 endRender 中增加
  }

  endRender(fieldId: string) {
    if (!this.isRenderMonitoringEnabled) return;

    const endTime = performance.now();
    const renderTime = endTime - this.fieldMetrics[fieldId].lastRenderTime;

    this.fieldMetrics[fieldId].renderCount++;
    this.renderMetrics.renderCount++; // 在这里增加总渲染次数
    this.renderMetrics.renderTime += renderTime;

    log.renderPerformance(LogCategory.PERFORMANCE_MONITOR, fieldId, 'end', renderTime);
  }

  skipRender(fieldId: string) {
    if (!this.isRenderMonitoringEnabled) return;

    if (!this.fieldMetrics[fieldId]) {
      this.fieldMetrics[fieldId] = {
        renderCount: 0,
        lastRenderTime: 0,
        skippedCount: 0
      };
    }

    this.fieldMetrics[fieldId].skippedCount++;
    this.renderMetrics.skippedRenders++;

    log.renderPerformance(LogCategory.PERFORMANCE_MONITOR, fieldId, 'skip');
  }

  setTotalFields(count: number) {
    this.renderMetrics.totalFields = count;
  }

  getRenderMetrics(): RenderMetrics {
    return { ...this.renderMetrics };
  }

  getFieldMetrics(): FieldRenderMetrics {
    return { ...this.fieldMetrics };
  }

  printRenderReport() {
    if (!this.isRenderMonitoringEnabled) return;

    const duration = Date.now() - this.renderMetrics.timestamp;
    const avgRenderTime =
      this.renderMetrics.renderCount > 0
        ? this.renderMetrics.renderTime / this.renderMetrics.renderCount
        : 0;

    const optimizationRate =
      this.renderMetrics.renderCount + this.renderMetrics.skippedRenders > 0
        ? (this.renderMetrics.skippedRenders /
            (this.renderMetrics.renderCount + this.renderMetrics.skippedRenders)) *
          100
        : 0;

    const metrics = {
      renderCount: this.renderMetrics.renderCount,
      skippedRenders: this.renderMetrics.skippedRenders,
      renderTime: this.renderMetrics.renderTime,
      optimizationRate,
      avgRenderTime,
      totalFields: this.renderMetrics.totalFields,
      duration
    };

    log.performanceReport(LogCategory.PERFORMANCE_MONITOR, metrics);
    log.fieldPerformanceDetails(LogCategory.PERFORMANCE_MONITOR, this.fieldMetrics);
  }

  // ==================== 通用性能测试 ====================

  startTimer(name: string): void {
    this.timers.set(name, performance.now());
  }

  endTimer(name: string): number {
    const startTime = this.timers.get(name);
    if (!startTime) {
      console.warn(`Timer ${name} was not started`);
      return 0;
    }

    const duration = performance.now() - startTime;
    this.timers.delete(name);

    // 记录指标
    if (!this.timerMetrics.has(name)) {
      this.timerMetrics.set(name, []);
    }
    this.timerMetrics.get(name)!.push(duration);

    log.performance(LogCategory.PERFORMANCE, name, duration);
    return duration;
  }

  getAverageTime(name: string): number {
    const times = this.timerMetrics.get(name);
    if (!times || times.length === 0) return 0;
    return times.reduce((sum, time) => sum + time, 0) / times.length;
  }

  getTimerMetrics(): Record<string, TimerMetrics> {
    const result: Record<string, TimerMetrics> = {};

    for (const [name, times] of this.timerMetrics.entries()) {
      const total = times.reduce((sum, time) => sum + time, 0);
      result[name] = {
        count: times.length,
        average: total / times.length,
        total
      };
    }

    return result;
  }

  logTimerSummary(): void {
    const metrics = this.getTimerMetrics();
    log.group(LogCategory.PERFORMANCE, '性能测试总结', () => {
      for (const [name, data] of Object.entries(metrics)) {
        log.info(LogCategory.PERFORMANCE, `${name}:`);
        log.info(LogCategory.PERFORMANCE, `  执行次数: ${data.count}`);
        log.info(LogCategory.PERFORMANCE, `  平均时间: ${data.average.toFixed(2)}ms`);
        log.info(LogCategory.PERFORMANCE, `  总时间: ${data.total.toFixed(2)}ms`);
      }
    });
  }

  // ==================== 批量更新性能测试 ====================

  compareUpdatePerformance() {
    const testData = {
      field1: 'value1',
      field2: 'value2',
      field3: 'value3',
      field4: 'value4',
      field5: 'value5'
    };

    // 测试单个更新
    this.startTimer('individual-updates');
    Object.entries(testData).forEach(([fieldId, value]) => {
      // 模拟单个 dispatch
      log.info(LogCategory.PERFORMANCE, `Dispatch SET_FIELD_VALUE: ${fieldId} = ${value}`);
    });
    this.endTimer('individual-updates');

    // 测试批量更新
    this.startTimer('batch-update');
    log.info(LogCategory.PERFORMANCE, 'Dispatch SET_FIELD_VALUES:', testData);
    this.endTimer('batch-update');

    // 输出性能对比
    const individualTime = this.getAverageTime('individual-updates');
    const batchTime = this.getAverageTime('batch-update');

    log.group(LogCategory.PERFORMANCE, '性能对比', () => {
      log.info(LogCategory.PERFORMANCE, `单个更新: ${individualTime.toFixed(2)}ms`);
      log.info(LogCategory.PERFORMANCE, `批量更新: ${batchTime.toFixed(2)}ms`);
      log.info(
        LogCategory.PERFORMANCE,
        `性能提升: ${(((individualTime - batchTime) / individualTime) * 100).toFixed(2)}%`
      );
    });
  }

  // ==================== 统一管理 ====================

  reset(): void {
    // 重置渲染监控
    this.renderMetrics = {
      renderCount: 0,
      renderTime: 0,
      skippedRenders: 0,
      totalFields: 0,
      timestamp: Date.now()
    };
    this.fieldMetrics = {};

    // 重置计时器
    this.timers.clear();
    this.timerMetrics.clear();
  }

  // 对比基准性能
  compareWithBaseline(baselineMetrics: RenderMetrics) {
    if (!this.isRenderMonitoringEnabled) return;

    const currentMetrics = this.getRenderMetrics();
    const renderTimeDiff = currentMetrics.renderTime - baselineMetrics.renderTime;
    const renderCountDiff = currentMetrics.renderCount - baselineMetrics.renderCount;
    const optimizationDiff = currentMetrics.skippedRenders - baselineMetrics.skippedRenders;

    log.group(LogCategory.PERFORMANCE_MONITOR, '🔍 性能对比报告', () => {
      log.info(
        LogCategory.PERFORMANCE_MONITOR,
        `⏱️  渲染时间差异: ${renderTimeDiff > 0 ? '+' : ''}${renderTimeDiff.toFixed(2)}ms`
      );
      log.info(
        LogCategory.PERFORMANCE_MONITOR,
        `📈 渲染次数差异: ${renderCountDiff > 0 ? '+' : ''}${renderCountDiff}`
      );
      log.info(
        LogCategory.PERFORMANCE_MONITOR,
        `⏭️  优化次数差异: ${optimizationDiff > 0 ? '+' : ''}${optimizationDiff}`
      );

      if (renderTimeDiff < 0) {
        log.info(LogCategory.PERFORMANCE_MONITOR, '✅ 性能有所提升');
      } else if (renderTimeDiff > 0) {
        log.info(LogCategory.PERFORMANCE_MONITOR, '⚠️  性能有所下降');
      } else {
        log.info(LogCategory.PERFORMANCE_MONITOR, '➡️  性能基本持平');
      }
    });
  }
}

// 创建全局性能监控实例
export const performanceMonitor = UnifiedPerformanceMonitor.getInstance();

// 性能监控 Hook
export function usePerformanceMonitor() {
  const startTimer = (name: string) => performanceMonitor.startTimer(name);
  const endTimer = (name: string) => performanceMonitor.endTimer(name);
  const logSummary = () => performanceMonitor.logTimerSummary();

  return { startTimer, endTimer, logSummary };
}

// 渲染性能监控 Hook
export function useRenderPerformanceMonitor() {
  const startRender = (fieldId: string) => performanceMonitor.startRender(fieldId);
  const endRender = (fieldId: string) => performanceMonitor.endRender(fieldId);
  const skipRender = (fieldId: string) => performanceMonitor.skipRender(fieldId);
  const printReport = () => performanceMonitor.printRenderReport();

  return { startRender, endRender, skipRender, printReport };
}
